<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>物联网设备控制中心</title>
    <!-- 引入外部资源 -->
    <script src="https://cdn.tailwindcss.com"></script>
    <link href="https://cdn.jsdelivr.net/npm/font-awesome@4.7.0/css/font-awesome.min.css" rel="stylesheet">
    <script src="https://cdn.jsdelivr.net/npm/echarts@5.4.3/dist/echarts.min.js"></script>
    
    <!-- 配置Tailwind自定义颜色 -->
    <script>
        tailwind.config = {
            theme: {
                extend: {
                    colors: {
                        primary: '#165DFF',
                        secondary: '#36CFC9',
                        success: '#00B42A',
                        danger: '#F53F3F',
                        warning: '#FF7D00',
                        info: '#86909C'
                    }
                }
            }
        }
    </script>
    
    <!-- 自定义工具类 -->
    <style type="text/tailwindcss">
        @layer utilities {
            .content-auto {
                content-visibility: auto;
            }
            .card-shadow {
                box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);
            }
            .device-card-hover {
                transition: all 0.3s ease;
            }
            .device-card-hover:hover {
                transform: translateY(-4px);
                box-shadow: 0 8px 24px rgba(0, 0, 0, 0.1);
            }
            .status-indicator {
                width: 10px;
                height: 10px;
                border-radius: 50%;
                display: inline-block;
            }
            .animate-fadeIn {
                animation: fadeIn 0.5s ease-in-out;
            }
            @keyframes fadeIn {
                from { opacity: 0; }
                to { opacity: 1; }
            }
        }
    </style>
</head>
<body class="bg-gray-50 min-h-screen font-sans">
    <!-- 登录页面 -->
    <div id="login-page" class="min-h-screen flex items-center justify-center p-4">
        <div class="w-full max-w-md bg-white rounded-2xl p-8 card-shadow">
            <div class="text-center mb-8">
                <div class="inline-flex items-center justify-center w-16 h-16 rounded-full bg-primary/10 text-primary mb-4">
                    <i class="fa fa-cogs text-2xl"></i>
                </div>
                <h1 class="text-2xl font-bold text-gray-800">设备控制中心</h1>
                <p class="text-gray-500 mt-2">请登录以访问设备控制界面</p>
            </div>
            
            <form id="login-form" class="space-y-4">
                <div>
                    <label for="username" class="block text-sm font-medium text-gray-700 mb-1">用户名</label>
                    <div class="relative">
                        <div class="absolute inset-y-0 left-0 pl-3 flex items-center pointer-events-none">
                            <i class="fa fa-user text-gray-400"></i>
                        </div>
                        <input type="text" id="username" name="username" required
                            class="block w-full pl-10 pr-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-primary focus:border-primary transition-all duration-300"
                            placeholder="请输入用户名">
                    </div>
                </div>
                
                <div>
                    <label for="password" class="block text-sm font-medium text-gray-700 mb-1">密码</label>
                    <div class="relative">
                        <div class="absolute inset-y-0 left-0 pl-3 flex items-center pointer-events-none">
                            <i class="fa fa-lock text-gray-400"></i>
                        </div>
                        <input type="password" id="password" name="password" required
                            class="block w-full pl-10 pr-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-primary focus:border-primary transition-all duration-300"
                            placeholder="请输入密码">
                    </div>
                </div>
                
                <div class="flex items-center justify-between">
                    <div class="flex items-center">
                        <input id="remember-me" name="remember-me" type="checkbox"
                            class="h-4 w-4 text-primary focus:ring-primary border-gray-300 rounded">
                        <label for="remember-me" class="ml-2 block text-sm text-gray-700">
                            记住我
                        </label>
                    </div>
                    <a href="#" class="text-sm text-primary hover:text-primary/80 transition-colors duration-300">
                        忘记密码?
                    </a>
                </div>
                
                <button type="submit" 
                    class="w-full bg-primary hover:bg-primary/90 text-white font-medium py-2 px-4 rounded-lg transition-all duration-300 flex items-center justify-center">
                    <span>登录</span>
                    <i class="fa fa-arrow-right ml-2"></i>
                </button>
            </form>
            
            <div id="login-error" class="mt-4 text-danger text-sm hidden">
                <i class="fa fa-exclamation-circle mr-1"></i>
                <span>用户名或密码错误，请重试</span>
            </div>
        </div>
    </div>

    <!-- 主控制页面 (默认隐藏) -->
    <div id="control-page" class="hidden">
        <!-- 顶部导航栏 -->
        <header class="bg-white shadow-sm fixed top-0 left-0 right-0 z-30">
            <div class="container mx-auto px-4 py-3 flex justify-between items-center">
                <div class="flex items-center">
                    <i class="fa fa-cogs text-primary text-xl mr-2"></i>
                    <h1 class="text-lg font-bold text-gray-800">物联网设备控制中心</h1>
                </div>
                
                <div class="flex items-center space-x-6">
                    <div class="hidden md:flex items-center text-sm text-gray-600">
                        <i class="fa fa-clock-o mr-1"></i>
                        <span id="current-time">--:--:--</span>
                    </div>
                    
                    <div class="flex items-center">
                        <span id="user-info" class="hidden md:inline-block mr-2 text-sm font-medium">管理员</span>
                        <button id="logout-btn" class="text-gray-500 hover:text-danger transition-colors duration-300">
                            <i class="fa fa-sign-out"></i>
                        </button>
                    </div>
                </div>
            </div>
        </header>

        <!-- 系统状态概览 -->
        <div class="bg-primary text-white py-2 mt-16">
            <div class="container mx-auto px-4">
                <div class="flex flex-wrap items-center justify-between">
                    <div class="flex items-center mb-2 md:mb-0">
                        <i class="fa fa-server mr-2"></i>
                        <span>系统状态: </span>
                        <span id="system-status-indicator" class="ml-2 px-2 py-0.5 bg-success/20 text-success text-xs rounded-full flex items-center">
                            <span class="w-1.5 h-1.5 bg-success rounded-full mr-1 animate-pulse"></span>
                            正常运行中
                        </span>
                    </div>
                    <div class="text-xs text-white/80">
                        协议版本: v1.0 | MQTT服务器: <span id="mqtt-server-status">未连接</span> | 数据更新间隔: 3秒
                    </div>
                </div>
            </div>
        </div>

        <!-- 主内容区 -->
        <main class="container mx-auto px-4 py-6">
            <!-- 快速状态卡片 -->
            <section class="my-6 grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-4">
                <div class="bg-white rounded-xl p-4 shadow-sm device-card-hover">
                    <div class="flex justify-between items-start">
                        <div>
                            <p class="text-gray-500 text-sm">在线设备</p>
                            <p class="text-2xl font-bold mt-1 text-success" id="online-devices">14</p>
                            <p class="text-xs text-gray-500 mt-1">共15台设备</p>
                        </div>
                        <div class="w-10 h-10 rounded-full bg-success/10 flex items-center justify-center text-success">
                            <i class="fa fa-plug"></i>
                        </div>
                    </div>
                </div>
                
                <div class="bg-white rounded-xl p-4 shadow-sm device-card-hover">
                    <div class="flex justify-between items-start">
                        <div>
                            <p class="text-gray-500 text-sm">当前温度</p>
                            <p class="text-2xl font-bold mt-1 text-primary" id="current-temp">24.5°C</p>
                            <p class="text-xs text-gray-500 mt-1">来自温度传感器</p>
                        </div>
                        <div class="w-10 h-10 rounded-full bg-primary/10 flex items-center justify-center text-primary">
                            <i class="fa fa-thermometer-half"></i>
                        </div>
                    </div>
                </div>
                
                <div class="bg-white rounded-xl p-4 shadow-sm device-card-hover">
                    <div class="flex justify-between items-start">
                        <div>
                            <p class="text-gray-500 text-sm">当前湿度</p>
                            <p class="text-2xl font-bold mt-1 text-secondary" id="current-humidity">48%</p>
                            <p class="text-xs text-gray-500 mt-1">来自湿度传感器</p>
                        </div>
                        <div class="w-10 h-10 rounded-full bg-secondary/10 flex items-center justify-center text-secondary">
                            <i class="fa fa-tint"></i>
                        </div>
                    </div>
                </div>
                
                <div class="bg-white rounded-xl p-4 shadow-sm device-card-hover">
                    <div class="flex justify-between items-start">
                        <div>
                            <p class="text-gray-500 text-sm">警报状态</p>
                            <p class="text-2xl font-bold mt-1 text-success" id="alarm-status">正常</p>
                            <p class="text-xs text-gray-500 mt-1">无异常情况</p>
                        </div>
                        <div class="w-10 h-10 rounded-full bg-success/10 flex items-center justify-center text-success">
                            <i class="fa fa-bell-o"></i>
                        </div>
                    </div>
                </div>
            </section>
            
            <!-- 温湿度趋势图和监控画面 -->
            <section class="my-6 grid grid-cols-1 lg:grid-cols-2 gap-6">
                <div class="bg-white rounded-xl p-5 shadow-sm">
                    <div class="flex justify-between items-center mb-4">
                        <h2 class="text-lg font-bold text-gray-800">温湿度趋势图</h2>
                        <div class="flex space-x-2">
                            <button class="time-filter px-3 py-1 text-xs bg-primary text-white rounded-full" data-range="hour">1小时</button>
                            <button class="time-filter px-3 py-1 text-xs bg-gray-100 hover:bg-gray-200 rounded-full transition-all duration-300" data-range="day">24小时</button>
                            <button class="time-filter px-3 py-1 text-xs bg-gray-100 hover:bg-gray-200 rounded-full transition-all duration-300" data-range="week">7天</button>
                        </div>
                    </div>
                    <div id="temp-humidity-chart" class="w-full h-[300px]"></div>
                </div>
                
                <!-- 监控画面 (使用实际外设视频流) -->
                <div class="bg-white rounded-xl p-5 shadow-sm">
                    <div class="flex justify-between items-center mb-4">
                        <h2 class="text-lg font-bold text-gray-800">监控画面</h2>
                        <button id="refresh-monitor" class="text-primary text-sm flex items-center hover:underline">
                            <i class="fa fa-refresh mr-1"></i>
                            <span>刷新</span>
                        </button>
                    </div>
                    <div class="relative bg-gray-100 rounded-lg overflow-hidden monitor-area">
                        <!-- 嵌入外设视频流，这里使用占位符，请替换为实际的外设IP -->
                        <iframe src="http://外设IP:8080/stream_simple.html" 
                                width="100%" height="300" frameborder="0" 
                                class="w-full h-[300px] object-cover"
                                alt="设备监控视频流"></iframe>
                        <div class="absolute top-2 right-2 bg-primary/80 text-white text-xs px-2 py-1 rounded-full flex items-center">
                            <span class="w-2 h-2 bg-red-500 rounded-full mr-1 animate-pulse"></span>
                            实时监控
                        </div>
                    </div>
                    <div class="text-xs text-gray-500 mt-2">
                        <i class="fa fa-info-circle mr-1"></i>
                        监控视频流来自外设IP:8080
                    </div>
                </div>
            </section>
            
            <!-- 设备控制选项卡 -->
            <section class="my-6">
                <div class="bg-white rounded-xl shadow-sm overflow-hidden">
                    <!-- 选项卡导航 -->
                    <div class="border-b border-gray-200">
                        <div class="flex overflow-x-auto">
                            <button class="device-tab py-4 px-6 text-primary border-b-2 border-primary font-medium whitespace-nowrap" data-tab="stm32">
                                STM32 设备
                            </button>
                            <button class="device-tab py-4 px-6 text-gray-500 hover:text-gray-700 border-b-2 border-transparent whitespace-nowrap" data-tab="modbus">
                                Modbus 设备
                            </button>
                            <button class="device-tab py-4 px-6 text-gray-500 hover:text-gray-700 border-b-2 border-transparent whitespace-nowrap" data-tab="metaServer">
                                元服务器设备
                            </button>
                        </div>
                    </div>
                    
                    <!-- STM32设备控制区 -->
                    <div class="device-content p-5" id="stm32-content">
                        <h2 class="text-lg font-bold text-gray-800 mb-4">STM32 设备控制</h2>
                        <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-5">
                            <!-- 冷藏柜 -->
                            <div class="border border-gray-100 rounded-xl p-4 device-card-hover">
                                <div class="flex justify-between items-start mb-3">
                                    <div>
                                        <h3 class="font-bold text-gray-800">冷藏柜</h3>
                                        <p class="text-sm text-gray-500 mt-1">
                                            <span class="status-indicator bg-success mr-1"></span>
                                            当前状态: <span id="status-1001" class="text-success">运行中</span>
                                        </p>
                                    </div>
                                    <div class="w-10 h-10 rounded-full bg-primary/10 flex items-center justify-center text-primary">
                                        <i class="fa fa-snowflake-o"></i>
                                    </div>
                                </div>
                                
                                <div class="flex items-center justify-between mt-2">
                                    <span class="text-xs text-gray-500">可控制</span>
                                    <label class="relative inline-flex items-center cursor-pointer">
                                        <input type="checkbox" class="sr-only peer device-toggle" data-key="1001" checked>
                                        <div class="w-11 h-6 bg-gray-200 peer-focus:outline-none peer-focus:ring-2 peer-focus:ring-primary rounded-full peer peer-checked:after:translate-x-full peer-checked:after:border-white after:content-[''] after:absolute after:top-[2px] after:left-[2px] after:bg-white after:border-gray-300 after:border after:rounded-full after:h-5 after:w-5 after:transition-all peer-checked:bg-primary"></div>
                                    </label>
                                </div>
                            </div>
                            
                            <!-- 电源插座 -->
                            <div class="border border-gray-100 rounded-xl p-4 device-card-hover">
                                <div class="flex justify-between items-start mb-3">
                                    <div>
                                        <h3 class="font-bold text-gray-800">电源插座</h3>
                                        <p class="text-sm text-gray-500 mt-1">
                                            <span class="status-indicator bg-success mr-1"></span>
                                            当前状态: <span id="status-1002" class="text-success">已通电</span>
                                        </p>
                                    </div>
                                    <div class="w-10 h-10 rounded-full bg-warning/10 flex items-center justify-center text-warning">
                                        <i class="fa fa-power-off"></i>
                                    </div>
                                </div>
                                
                                <div class="flex items-center justify-between mt-2">
                                    <span class="text-xs text-gray-500">可控制</span>
                                    <label class="relative inline-flex items-center cursor-pointer">
                                        <input type="checkbox" class="sr-only peer device-toggle" data-key="1002" checked>
                                        <div class="w-11 h-6 bg-gray-200 peer-focus:outline-none peer-focus:ring-2 peer-focus:ring-primary rounded-full peer peer-checked:after:translate-x-full peer-checked:after:border-white after:content-[''] after:absolute after:top-[2px] after:left-[2px] after:bg-white after:border-gray-300 after:border after:rounded-full after:h-5 after:w-5 after:transition-all peer-checked:bg-primary"></div>
                                    </label>
                                </div>
                            </div>
                            
                            <!-- 门锁 -->
                            <div class="border border-gray-100 rounded-xl p-4 device-card-hover">
                                <div class="flex justify-between items-start mb-3">
                                    <div>
                                        <h3 class="font-bold text-gray-800">门锁</h3>
                                        <p class="text-sm text-gray-500 mt-1">
                                            <span class="status-indicator bg-danger mr-1"></span>
                                            当前状态: <span id="status-1003" class="text-danger">已关锁</span>
                                        </p>
                                    </div>
                                    <div class="w-10 h-10 rounded-full bg-danger/10 flex items-center justify-center text-danger">
                                        <i class="fa fa-lock"></i>
                                    </div>
                                </div>
                                
                                <div class="flex items-center justify-between mt-2">
                                    <span class="text-xs text-gray-500">可控制</span>
                                    <label class="relative inline-flex items-center cursor-pointer">
                                        <input type="checkbox" class="sr-only peer device-toggle" data-key="1003">
                                        <div class="w-11 h-6 bg-gray-200 peer-focus:outline-none peer-focus:ring-2 peer-focus:ring-primary rounded-full peer peer-checked:after:translate-x-full peer-checked:after:border-white after:content-[''] after:absolute after:top-[2px] after:left-[2px] after:bg-white after:border-gray-300 after:border after:rounded-full after:h-5 after:w-5 after:transition-all peer-checked:bg-primary"></div>
                                    </label>
                                </div>
                            </div>
                            
                            <!-- 室内是否有人 -->
                            <div class="border border-gray-100 rounded-xl p-4 device-card-hover">
                                <div class="flex justify-between items-start mb-3">
                                    <div>
                                        <h3 class="font-bold text-gray-800">室内是否有人</h3>
                                        <p class="text-sm text-gray-500 mt-1">
                                            <span class="status-indicator bg-success mr-1"></span>
                                            当前状态: <span id="status-1004" class="text-success">有人</span>
                                        </p>
                                    </div>
                                    <div class="w-10 h-10 rounded-full bg-info/10 flex items-center justify-center text-info">
                                        <i class="fa fa-user"></i>
                                    </div>
                                </div>
                                
                                <div class="flex items-center justify-between mt-2">
                                    <span class="text-xs text-gray-500">只读</span>
                                    <span class="text-xs text-gray-400">传感器数据</span>
                                </div>
                            </div>
                            
                            <!-- 排风扇 -->
                            <div class="border border-gray-100 rounded-xl p-4 device-card-hover">
                                <div class="flex justify-between items-start mb-3">
                                    <div>
                                        <h3 class="font-bold text-gray-800">排风扇</h3>
                                        <p class="text-sm text-gray-500 mt-1">
                                            <span class="status-indicator bg-danger mr-1"></span>
                                            当前状态: <span id="status-1005" class="text-danger">已关闭</span>
                                        </p>
                                    </div>
                                    <div class="w-10 h-10 rounded-full bg-secondary/10 flex items-center justify-center text-secondary">
                                        <i class="fa fa-fan"></i>
                                    </div>
                                </div>
                                
                                <div class="flex items-center justify-between mt-2">
                                    <span class="text-xs text-gray-500">可控制</span>
                                    <label class="relative inline-flex items-center cursor-pointer">
                                        <input type="checkbox" class="sr-only peer device-toggle" data-key="1005">
                                        <div class="w-11 h-6 bg-gray-200 peer-focus:outline-none peer-focus:ring-2 peer-focus:ring-primary rounded-full peer peer-checked:after:translate-x-full peer-checked:after:border-white after:content-[''] after:absolute after:top-[2px] after:left-[2px] after:bg-white after:border-gray-300 after:border after:rounded-full after:h-5 after:w-5 after:transition-all peer-checked:bg-primary"></div>
                                    </label>
                                </div>
                            </div>
                            
                            <!-- 灯光状态 -->
                            <div class="border border-gray-100 rounded-xl p-4 device-card-hover">
                                <div class="flex justify-between items-start mb-3">
                                    <div>
                                        <h3 class="font-bold text-gray-800">灯光状态</h3>
                                        <p class="text-sm text-gray-500 mt-1">
                                            <span class="status-indicator bg-danger mr-1"></span>
                                            当前状态: <span id="status-1006" class="text-danger">已关闭</span>
                                        </p>
                                    </div>
                                    <div class="w-10 h-10 rounded-full bg-warning/10 flex items-center justify-center text-warning">
                                        <i class="fa fa-lightbulb-o"></i>
                                    </div>
                                </div>
                                
                                <div class="flex items-center justify-between mt-2">
                                    <span class="text-xs text-gray-500">只读</span>
                                    <span class="text-xs text-gray-400">传感器数据</span>
                                </div>
                            </div>
                            
                            <!-- 温度传感器 -->
                            <div class="border border-gray-100 rounded-xl p-4 device-card-hover">
                                <div class="flex justify-between items-start mb-3">
                                    <div>
                                        <h3 class="font-bold text-gray-800">温度传感器</h3>
                                        <p class="text-sm text-gray-500 mt-1">
                                            <span class="status-indicator bg-success mr-1"></span>
                                            当前值: <span id="value-1007" class="text-primary">24.5°C</span>
                                        </p>
                                    </div>
                                    <div class="w-10 h-10 rounded-full bg-primary/10 flex items-center justify-center text-primary">
                                        <i class="fa fa-thermometer-half"></i>
                                    </div>
                                </div>
                                
                                <div class="flex items-center justify-between mt-2">
                                    <span class="text-xs text-gray-500">只读</span>
                                    <span class="text-xs text-gray-400">传感器数据</span>
                                </div>
                            </div>
                            
                            <!-- 湿度传感器 -->
                            <div class="border border-gray-100 rounded-xl p-4 device-card-hover">
                                <div class="flex justify-between items-start mb-3">
                                    <div>
                                        <h3 class="font-bold text-gray-800">湿度传感器</h3>
                                        <p class="text-sm text-gray-500 mt-1">
                                            <span class="status-indicator bg-success mr-1"></span>
                                            当前值: <span id="value-1008" class="text-secondary">48%</span>
                                        </p>
                                    </div>
                                    <div class="w-10 h-10 rounded-full bg-secondary/10 flex items-center justify-center text-secondary">
                                        <i class="fa fa-tint"></i>
                                    </div>
                                </div>
                                
                                <div class="flex items-center justify-between mt-2">
                                    <span class="text-xs text-gray-500">只读</span>
                                    <span class="text-xs text-gray-400">传感器数据</span>
                                </div>
                            </div>
                            
                            <!-- 险情警报 -->
                            <div class="border border-gray-100 rounded-xl p-4 device-card-hover">
                                <div class="flex justify-between items-start mb-3">
                                    <div>
                                        <h3 class="font-bold text-gray-800">险情警报</h3>
                                        <p class="text-sm text-gray-500 mt-1">
                                            <span class="status-indicator bg-success mr-1"></span>
                                            当前状态: <span id="status-1009" class="text-success">正常</span>
                                        </p>
                                    </div>
                                    <div class="w-10 h-10 rounded-full bg-danger/10 flex items-center justify-center text-danger">
                                        <i class="fa fa-exclamation-triangle"></i>
                                    </div>
                                </div>
                                
                                <div class="flex items-center justify-between mt-2">
                                    <span class="text-xs text-gray-500">可控制</span>
                                    <label class="relative inline-flex items-center cursor-pointer">
                                        <input type="checkbox" class="sr-only peer device-toggle" data-key="1009">
                                        <div class="w-11 h-6 bg-gray-200 peer-focus:outline-none peer-focus:ring-2 peer-focus:ring-primary rounded-full peer peer-checked:after:translate-x-full peer-checked:after:border-white after:content-[''] after:absolute after:top-[2px] after:left-[2px] after:bg-white after:border-gray-300 after:border after:rounded-full after:h-5 after:w-5 after:transition-all peer-checked:bg-primary"></div>
                                    </label>
                                </div>
                            </div>
                        </div>
                    </div>
                    
                    <!-- Modbus设备控制区 -->
                    <div class="device-content p-5 hidden" id="modbus-content">
                        <h2 class="text-lg font-bold text-gray-800 mb-4">Modbus 设备控制</h2>
                        <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-5">
                            <!-- 空调模式 -->
                            <div class="border border-gray-100 rounded-xl p-4 device-card-hover">
                                <div class="flex justify-between items-start mb-3">
                                    <div>
                                        <h3 class="font-bold text-gray-800">空调模式</h3>
                                        <p class="text-sm text-gray-500 mt-1">
                                            <span class="status-indicator bg-success mr-1"></span>
                                            当前模式: <span id="status-2001" class="text-primary">制冷</span>
                                        </p>
                                    </div>
                                    <div class="w-10 h-10 rounded-full bg-primary/10 flex items-center justify-center text-primary">
                                        <i class="fa fa-snowflake-o"></i>
                                    </div>
                                </div>
                                
                                <div class="flex flex-wrap gap-2 mt-3">
                                    <button class="device-command px-3 py-1 text-xs bg-primary text-white rounded-full" data-key="2001" data-cmd="11">制冷</button>
                                    <button class="device-command px-3 py-1 text-xs bg-gray-100 hover:bg-gray-200 rounded-full transition-all duration-300" data-key="2001" data-cmd="22">制热</button>
                                    <button class="device-command px-3 py-1 text-xs bg-gray-100 hover:bg-gray-200 rounded-full transition-all duration-300" data-key="2001" data-cmd="33">除湿</button>
                                </div>
                            </div>
                            
                            <!-- 窗帘控制 -->
                            <div class="border border-gray-100 rounded-xl p-4 device-card-hover">
                                <div class="flex justify-between items-start mb-3">
                                    <div>
                                        <h3 class="font-bold text-gray-800">窗帘控制</h3>
                                        <p class="text-sm text-gray-500 mt-1">
                                            <span class="status-indicator bg-success mr-1"></span>
                                            当前位置: <span id="status-2002" class="text-primary">70%</span>
                                        </p>
                                    </div>
                                    <div class="w-10 h-10 rounded-full bg-secondary/10 flex items-center justify-center text-secondary">
                                        <i class="fa fa-columns"></i>
                                    </div>
                                </div>
                                
                                <div class="mt-3">
                                    <input type="range" min="0" max="100" value="70" class="w-full device-slider" data-key="2002">
                                    <div class="flex justify-between text-xs text-gray-500 mt-1">
                                        <span>关闭</span>
                                        <span>全开</span>
                                    </div>
                                </div>
                            </div>
                            
                            <!-- 窗户控制 -->
                            <div class="border border-gray-100 rounded-xl p-4 device-card-hover">
                                <div class="flex justify-between items-start mb-3">
                                    <div>
                                        <h3 class="font-bold text-gray-800">窗户控制</h3>
                                        <p class="text-sm text-gray-500 mt-1">
                                            <span class="status-indicator bg-danger mr-1"></span>
                                            当前状态: <span id="status-2003" class="text-danger">关闭</span>
                                        </p>
                                    </div>
                                    <div class="w-10 h-10 rounded-full bg-info/10 flex items-center justify-center text-info">
                                        <i class="fa fa-window-maximize"></i>
                                    </div>
                                </div>
                                
                                <div class="flex items-center justify-between mt-2">
                                    <span class="text-xs text-gray-500">可控制</span>
                                    <label class="relative inline-flex items-center cursor-pointer">
                                        <input type="checkbox" class="sr-only peer device-toggle" data-key="2003">
                                        <div class="w-11 h-6 bg-gray-200 peer-focus:outline-none peer-focus:ring-2 peer-focus:ring-primary rounded-full peer peer-checked:after:translate-x-full peer-checked:after:border-white after:content-[''] after:absolute after:top-[2px] after:left-[2px] after:bg-white after:border-gray-300 after:border after:rounded-full after:h-5 after:w-5 after:transition-all peer-checked:bg-primary"></div>
                                    </label>
                                </div>
                            </div>
                            
                            <!-- 商超广告大屏 -->
                            <div class="border border-gray-100 rounded-xl p-4 device-card-hover">
                                <div class="flex justify-between items-start mb-3">
                                    <div>
                                        <h3 class="font-bold text-gray-800">商超广告大屏</h3>
                                        <p class="text-sm text-gray-500 mt-1">
                                            <span class="status-indicator bg-success mr-1"></span>
                                            当前状态: <span id="status-2004" class="text-success">开启</span>
                                        </p>
                                    </div>
                                    <div class="w-10 h-10 rounded-full bg-warning/10 flex items-center justify-center text-warning">
                                        <i class="fa fa-television"></i>
                                    </div>
                                </div>
                                
                                <div class="flex items-center justify-between mt-2">
                                    <span class="text-xs text-gray-500">可控制</span>
                                    <label class="relative inline-flex items-center cursor-pointer">
                                        <input type="checkbox" class="sr-only peer device-toggle" data-key="2004" checked>
                                        <div class="w-11 h-6 bg-gray-200 peer-focus:outline-none peer-focus:ring-2 peer-focus:ring-primary rounded-full peer peer-checked:after:translate-x-full peer-checked:after:border-white after:content-[''] after:absolute after:top-[2px] after:left-[2px] after:bg-white after:border-gray-300 after:border after:rounded-full after:h-5 after:w-5 after:transition-all peer-checked:bg-primary"></div>
                                    </label>
                                </div>
                            </div>
                            
                            <!-- 水产水量控制 -->
                            <div class="border border-gray-100 rounded-xl p-4 device-card-hover">
                                <div class="flex justify-between items-start mb-3">
                                    <div>
                                        <h3 class="font-bold text-gray-800">水产水量控制</h3>
                                        <p class="text-sm text-gray-500 mt-1">
                                            <span class="status-indicator bg-success mr-1"></span>
                                            当前水量: <span id="status-2005" class="text-primary">50%</span>
                                        </p>
                                    </div>
                                    <div class="w-10 h-10 rounded-full bg-secondary/10 flex items-center justify-center text-secondary">
                                        <i class="fa fa-tint"></i>
                                    </div>
                                </div>
                                
                                <div class="mt-3">
                                    <input type="range" min="0" max="100" value="50" class="w-full device-slider" data-key="2005">
                                    <div class="flex justify-between text-xs text-gray-500 mt-1">
                                        <span>最低</span>
                                        <span>最高</span>
                                    </div>
                                </div>
                            </div>
                            
                            <!-- 空调电源状态 -->
                            <div class="border border-gray-100 rounded-xl p-4 device-card-hover">
                                <div class="flex justify-between items-start mb-3">
                                    <div>
                                        <h3 class="font-bold text-gray-800">空调电源状态</h3>
                                        <p class="text-sm text-gray-500 mt-1">
                                            <span class="status-indicator bg-success mr-1"></span>
                                            当前状态: <span id="status-2006" class="text-success">开启</span>
                                        </p>
                                    </div>
                                    <div class="w-10 h-10 rounded-full bg-primary/10 flex items-center justify-center text-primary">
                                        <i class="fa fa-power-off"></i>
                                    </div>
                                </div>
                                
                                <div class="flex items-center justify-between mt-2">
                                    <span class="text-xs text-gray-500">可控制</span>
                                    <label class="relative inline-flex items-center cursor-pointer">
                                        <input type="checkbox" class="sr-only peer device-toggle" data-key="2006" checked>
                                        <div class="w-11 h-6 bg-gray-200 peer-focus:outline-none peer-focus:ring-2 peer-focus:ring-primary rounded-full peer peer-checked:after:translate-x-full peer-checked:after:border-white after:content-[''] after:absolute after:top-[2px] after:left-[2px] after:bg-white after:border-gray-300 after:border after:rounded-full after:h-5 after:w-5 after:transition-all peer-checked:bg-primary"></div>
                                    </label>
                                </div>
                            </div>
                        </div>
                    </div>
                    
                    <!-- 元服务器设备控制区 -->
                    <div class="device-content p-5 hidden" id="metaServer-content">
                        <h2 class="text-lg font-bold text-gray-800 mb-4">元服务器设备控制</h2>
                        <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-5">
                            <!-- 人体红外检测 -->
                            <div class="border border-gray-100 rounded-xl p-4 device-card-hover">
                                <div class="flex justify-between items-start mb-3">
                                    <div>
                                        <h3 class="font-bold text-gray-800">人体红外检测</h3>
                                        <p class="text-sm text-gray-500 mt-1">
                                            <span class="status-indicator bg-success mr-1"></span>
                                            当前状态: <span id="status-3001" class="text-success">检测到1人</span>
                                        </p>
                                    </div>
                                    <div class="w-10 h-10 rounded-full bg-info/10 flex items-center justify-center text-info">
                                        <i class="fa fa-user-secret"></i>
                                    </div>
                                </div>
                                
                                <div class="flex items-center justify-between mt-2">
                                    <span class="text-xs text-gray-500">只读</span>
                                    <span class="text-xs text-gray-400">传感器数据</span>
                                </div>
                            </div>
                            
                            <!-- 烟感控制 -->
                            <div class="border border-gray-100 rounded-xl p-4 device-card-hover">
                                <div class="flex justify-between items-start mb-3">
                                    <div>
                                        <h3 class="font-bold text-gray-800">烟感控制</h3>
                                        <p class="text-sm text-gray-500 mt-1">
                                            <span class="status-indicator bg-success mr-1"></span>
                                            当前状态: <span id="status-3002" class="text-success">正常</span>
                                        </p>
                                    </div>
                                    <div class="w-10 h-10 rounded-full bg-danger/10 flex items-center justify-center text-danger">
                                        <i class="fa fa-fire-extinguisher"></i>
                                    </div>
                                </div>
                                
                                <div class="flex items-center justify-between mt-2">
                                    <span class="text-xs text-gray-500">只读</span>
                                    <span class="text-xs text-gray-400">传感器数据</span>
                                </div>
                            </div>
                            
                            <!-- 遮阳板控制 -->
                            <div class="border border-gray-100 rounded-xl p-4 device-card-hover">
                                <div class="flex justify-between items-start mb-3">
                                    <div>
                                        <h3 class="font-bold text-gray-800">遮阳板控制</h3>
                                        <p class="text-sm text-gray-500 mt-1">
                                            <span class="status-indicator bg-success mr-1"></span>
                                            当前位置: <span id="status-3003" class="text-primary">30%</span>
                                        </p>
                                    </div>
                                    <div class="w-10 h-10 rounded-full bg-warning/10 flex items-center justify-center text-warning">
                                        <i class="fa fa-umbrella"></i>
                                    </div>
                                </div>
                                
                                <div class="mt-3">
                                    <input type="range" min="0" max="100" value="30" class="w-full device-slider" data-key="3003">
                                    <div class="flex justify-between text-xs text-gray-500 mt-1">
                                        <span>收起</span>
                                        <span>展开</span>
                                    </div>
                                </div>
                            </div>
                            
                            <!-- 通风设计 -->
                            <div class="border border-gray-100 rounded-xl p-4 device-card-hover">
                                <div class="flex justify-between items-start mb-3">
                                    <div>
                                        <h3 class="font-bold text-gray-800">通风设计</h3>
                                        <p class="text-sm text-gray-500 mt-1">
                                            <span class="status-indicator bg-danger mr-1"></span>
                                            当前状态: <span id="status-3004" class="text-danger">关闭</span>
                                        </p>
                                    </div>
                                    <div class="w-10 h-10 rounded-full bg-secondary/10 flex items-center justify-center text-secondary">
                                        <i class="fa fa-wind"></i>
                                    </div>
                                </div>
                                
                                <div class="flex items-center justify-between mt-2">
                                    <span class="text-xs text-gray-500">可控制</span>
                                    <label class="relative inline-flex items-center cursor-pointer">
                                        <input type="checkbox" class="sr-only peer device-toggle" data-key="3004">
                                        <div class="w-11 h-6 bg-gray-200 peer-focus:outline-none peer-focus:ring-2 peer-focus:ring-primary rounded-full peer peer-checked:after:translate-x-full peer-checked:after:border-white after:content-[''] after:absolute after:top-[2px] after:left-[2px] after:bg-white after:border-gray-300 after:border after:rounded-full after:h-5 after:w-5 after:transition-all peer-checked:bg-primary"></div>
                                    </label>
                                </div>
                            </div>
                            
                            <!-- 灯光控制 -->
                            <div class="border border-gray-100 rounded-xl p-4 device-card-hover">
                                <div class="flex justify-between items-start mb-3">
                                    <div>
                                        <h3 class="font-bold text-gray-800">灯光控制</h3>
                                        <p class="text-sm text-gray-500 mt-1">
                                            <span class="status-indicator bg-success mr-1"></span>
                                            当前亮度: <span id="status-3005" class="text-warning">70%</span>
                                        </p>
                                    </div>
                                    <div class="w-10 h-10 rounded-full bg-warning/10 flex items-center justify-center text-warning">
                                        <i class="fa fa-lightbulb-o"></i>
                                    </div>
                                </div>
                                
                                <div class="mt-3">
                                    <input type="range" min="0" max="100" value="70" class="w-full device-slider" data-key="3005">
                                    <div class="flex justify-between text-xs text-gray-500 mt-1">
                                        <span>最暗</span>
                                        <span>最亮</span>
                                    </div>
                                </div>
                            </div>
                            
                            <!-- 收银台钱锁控制 -->
                            <div class="border border-gray-100 rounded-xl p-4 device-card-hover">
                                <div class="flex justify-between items-start mb-3">
                                    <div>
                                        <h3 class="font-bold text-gray-800">收银台钱锁控制</h3>
                                        <p class="text-sm text-gray-500 mt-1">
                                            <span class="status-indicator bg-success mr-1"></span>
                                            当前状态: <span id="status-3006" class="text-success">开启</span>
                                        </p>
                                    </div>
                                    <div class="w-10 h-10 rounded-full bg-danger/10 flex items-center justify-center text-danger">
                                        <i class="fa fa-lock"></i>
                                    </div>
                                </div>
                                
                                <div class="flex items-center justify-between mt-2">
                                    <span class="text-xs text-gray-500">可控制</span>
                                    <label class="relative inline-flex items-center cursor-pointer">
                                        <input type="checkbox" class="sr-only peer device-toggle" data-key="3006" checked>
                                        <div class="w-11 h-6 bg-gray-200 peer-focus:outline-none peer-focus:ring-2 peer-focus:ring-primary rounded-full peer peer-checked:after:translate-x-full peer-checked:after:border-white after:content-[''] after:absolute after:top-[2px] after:left-[2px] after:bg-white after:border-gray-300 after:border after:rounded-full after:h-5 after:w-5 after:transition-all peer-checked:bg-primary"></div>
                                    </label>
                                </div>
                            </div>
                            
                            <!-- 安检设备控制 -->
                            <div class="border border-gray-100 rounded-xl p-4 device-card-hover">
                                <div class="flex justify-between items-start mb-3">
                                    <div>
                                        <h3 class="font-bold text-gray-800">安检设备控制</h3>
                                        <p class="text-sm text-gray-500 mt-1">
                                            <span class="status-indicator bg-success mr-1"></span>
                                            当前状态: <span id="status-3007" class="text-success">开启</span>
                                        </p>
                                    </div>
                                    <div class="w-10 h-10 rounded-full bg-primary/10 flex items-center justify-center text-primary">
                                        <i class="fa fa-shield"></i>
                                    </div>
                                </div>
                                
                                <div class="flex items-center justify-between mt-2">
                                    <span class="text-xs text-gray-500">可控制</span>
                                    <label class="relative inline-flex items-center cursor-pointer">
                                        <input type="checkbox" class="sr-only peer device-toggle" data-key="3007" checked>
                                        <div class="w-11 h-6 bg-gray-200 peer-focus:outline-none peer-focus:ring-2 peer-focus:ring-primary rounded-full peer peer-checked:after:translate-x-full peer-checked:after:border-white after:content-[''] after:absolute after:top-[2px] after:left-[2px] after:bg-white after:border-gray-300 after:border after:rounded-full after:h-5 after:w-5 after:transition-all peer-checked:bg-primary"></div>
                                    </label>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </section>
            
            <!-- 操作日志 -->
            <section class="my-6">
                <div class="bg-white rounded-xl p-5 shadow-sm">
                    <h2 class="text-lg font-bold text-gray-800 mb-4">操作日志</h2>
                    <div class="overflow-x-auto max-h-[200px] overflow-y-auto pr-2" id="operation-log">
                        <div class="text-sm text-gray-500 mb-2">
                            <span class="text-gray-400">[--:--:--]</span> 系统初始化完成
                        </div>
                    </div>
                </div>
            </section>
        </main>
        
        <!-- 页脚 -->
        <footer class="bg-white border-t border-gray-200 py-4 mt-auto">
            <div class="container mx-auto px-4 text-center text-gray-500 text-sm">
                <p>物联网设备控制中心 &copy; 2023</p>
                <p class="mt-1">协议版本: v1.0 | 数据每3秒自动更新</p>
            </div>
        </footer>
    </div>

    <!-- 通知提示组件 -->
    <div id="notification" class="fixed top-4 right-4 bg-white shadow-lg rounded-lg p-4 transform translate-x-full transition-all duration-300 flex items-center max-w-xs z-50">
        <div id="notification-icon" class="w-8 h-8 rounded-full flex items-center justify-center mr-3 bg-success/10 text-success">
            <i class="fa fa-check"></i>
        </div>
        <div>
            <h4 id="notification-title" class="font-medium text-gray-800">操作成功</h4>
            <p id="notification-message" class="text-sm text-gray-500 mt-1">设备已成功开启</p>
        </div>
        <button id="close-notification" class="ml-4 text-gray-400 hover:text-gray-600">
            <i class="fa fa-times"></i>
        </button>
    </div>

    <script>
        // 全局变量
        let tempHumidityChart = null;
        let isAuthenticated = false;
        let token = localStorage.getItem('iot_token');
        let deviceData = {}; // 存储设备数据
        let updateInterval = null;
        // 服务器配置 - 请根据实际情况修改
        const SERVER_URL = "http://localhost";  // 服务器地址
        const MQTT_CHECK_INTERVAL = 5000;      // MQTT连接检查间隔(ms)
        
        // 页面加载完成后初始化
        document.addEventListener('DOMContentLoaded', function() {
            // 初始化设备数据
            initDeviceData();
            
            // 检查是否已登录
            if (token) {
                // 模拟验证token
                setTimeout(() => {
                    isAuthenticated = true;
                    showControlPage();
                }, 500);
            } else {
                showLoginPage();
            }
            
            // 登录表单提交
            document.getElementById('login-form').addEventListener('submit', function(e) {
                e.preventDefault();
                handleLogin();
            });
            
            // 登出按钮
            document.getElementById('logout-btn').addEventListener('click', handleLogout);
            
            // 关闭通知
            document.getElementById('close-notification').addEventListener('click', hideNotification);
            
            // 设备控制开关
            document.querySelectorAll('.device-toggle').forEach(toggle => {
                toggle.addEventListener('change', handleDeviceToggle);
            });
            
            // 设备控制命令按钮
            document.querySelectorAll('.device-command').forEach(btn => {
                btn.addEventListener('click', handleDeviceCommand);
            });
            
            // 设备滑块控制
            document.querySelectorAll('.device-slider').forEach(slider => {
                slider.addEventListener('input', handleDeviceSlider);
                slider.addEventListener('change', handleDeviceSliderChange);
            });
            
            // 设备选项卡切换
            document.querySelectorAll('.device-tab').forEach(tab => {
                tab.addEventListener('click', function() {
                    // 切换选项卡样式
                    document.querySelectorAll('.device-tab').forEach(t => {
                        t.classList.remove('text-primary', 'border-primary');
                        t.classList.add('text-gray-500', 'border-transparent');
                    });
                    this.classList.remove('text-gray-500', 'border-transparent');
                    this.classList.add('text-primary', 'border-primary');
                    
                    // 切换内容显示
                    const tabName = this.getAttribute('data-tab');
                    document.querySelectorAll('.device-content').forEach(content => {
                        content.classList.add('hidden');
                    });
                    document.getElementById(`${tabName}-content`).classList.remove('hidden');
                });
            });
            
            // 时间过滤器
            document.querySelectorAll('.time-filter').forEach(filter => {
                filter.addEventListener('click', function() {
                    document.querySelectorAll('.time-filter').forEach(f => {
                        f.classList.remove('bg-primary', 'text-white');
                        f.classList.add('bg-gray-100', 'hover:bg-gray-200');
                    });
                    this.classList.remove('bg-gray-100', 'hover:bg-gray-200');
                    this.classList.add('bg-primary', 'text-white');
                    // 切换不同时间范围数据
                    updateChartData(this.getAttribute('data-range'));
                });
            });
            
            // 刷新监控画面
            document.getElementById('refresh-monitor').addEventListener('click', updateMonitoringImage);
        });
        
        // 初始化设备数据
        function initDeviceData() {
            // 初始化STM32设备数据
            deviceData['1001'] = { value: true, text: '运行中', type: 'bool' };
            deviceData['1002'] = { value: true, text: '已通电', type: 'bool' };
            deviceData['1003'] = { value: false, text: '已关锁', type: 'bool' };
            deviceData['1004'] = { value: true, text: '有人', type: 'bool' };
            deviceData['1005'] = { value: false, text: '已关闭', type: 'bool' };
            deviceData['1006'] = { value: false, text: '已关闭', type: 'bool' };
            deviceData['1007'] = { value: 24.5, text: '24.5°C', type: 'float' };
            deviceData['1008'] = { value: 48, text: '48%', type: 'float' };
            deviceData['1009'] = { value: false, text: '正常', type: 'bool' };
            
            // 初始化Modbus设备数据
            deviceData['2001'] = { value: 11, text: '制冷', type: 'int' };
            deviceData['2002'] = { value: 70, text: '70%', type: 'int' };
            deviceData['2003'] = { value: false, text: '关闭', type: 'bool' };
            deviceData['2004'] = { value: true, text: '开启', type: 'bool' };
            deviceData['2005'] = { value: 50, text: '50%', type: 'int' };
            deviceData['2006'] = { value: true, text: '开启', type: 'bool' };
            
            // 初始化元服务器设备数据
            deviceData['3001'] = { value: 1, text: '检测到1人', type: 'int' };
            deviceData['3002'] = { value: 0, text: '正常', type: 'int' };
            deviceData['3003'] = { value: 30, text: '30%', type: 'int' };
            deviceData['3004'] = { value: false, text: '关闭', type: 'bool' };
            deviceData['3005'] = { value: 70, text: '70%', type: 'int' };
            deviceData['3006'] = { value: true, text: '开启', type: 'bool' };
            deviceData['3007'] = { value: true, text: '开启', type: 'bool' };
        }
        
        // 显示登录页面
        function showLoginPage() {
            document.getElementById('login-page').classList.remove('hidden');
            document.getElementById('control-page').classList.add('hidden');
        }
        
        // 显示控制页面
        function showControlPage() {
            document.getElementById('login-page').classList.add('hidden');
            document.getElementById('control-page').classList.remove('hidden');
            
            // 初始化页面数据
            initTimeDisplay();
            updateDeviceDisplays();
            initChart();
            startDataUpdate();
            logOperation('系统初始化完成');
            
            // 定期检查MQTT连接状态
            setInterval(checkMqttConnection, MQTT_CHECK_INTERVAL);
        }
        
        // 处理登录
        function handleLogin() {
            const username = document.getElementById('username').value;
            const password = document.getElementById('password').value;
            const rememberMe = document.getElementById('remember-me').checked;
            
            // 发送登录请求到服务器
            fetch(`${SERVER_URL}/login`, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded',
                },
                body: `username=${encodeURIComponent(username)}&password=${encodeURIComponent(password)}`
            })
            .then(response => {
                if (!response.ok) {
                    throw new Error('登录失败');
                }
                return response.text();
            })
            .then(data => {
                // 登录成功
                isAuthenticated = true;
                token = 'iot_token_' + Date.now();
                
                // 保存token
                if (rememberMe) {
                    localStorage.setItem('iot_token', token);
                } else {
                    sessionStorage.setItem('iot_token', token);
                }
                
                // 显示控制页面
                showControlPage();
                logOperation('用户登录系统');
            })
            .catch(error => {
                console.error('登录失败:', error);
                document.getElementById('login-error').classList.remove('hidden');
                setTimeout(() => {
                    document.getElementById('login-error').classList.add('hidden');
                }, 3000);
            });
        }
        
        // 处理登出
        function handleLogout() {
            // 清除token
            localStorage.removeItem('iot_token');
            sessionStorage.removeItem('iot_token');
            token = null;
            isAuthenticated = false;
            
            // 清除定时更新
            if (updateInterval) {
                clearInterval(updateInterval);
                updateInterval = null;
            }
            
            // 显示登录页面
            showLoginPage();
            logOperation('用户退出系统');
        }
        
        // 初始化时间显示
        function initTimeDisplay() {
            function updateTime() {
                const now = new Date();
                const timeStr = now.toTimeString().slice(0, 8);
                document.getElementById('current-time').textContent = timeStr;
            }
            
            // 初始更新
            updateTime();
            // 每秒更新
            setInterval(updateTime, 1000);
        }
        
        // 初始化图表
        function initChart() {
            const chartDom = document.getElementById('temp-humidity-chart');
            tempHumidityChart = echarts.init(chartDom);
            
            // 初始数据
            const initialData = generateTimeSeriesData(60); // 1小时数据，每分钟一个点
            
            const option = {
                tooltip: {
                    trigger: 'axis',
                    axisPointer: {
                        type: 'cross'
                    }
                },
                legend: {
                    data: ['温度(°C)', '湿度(%)'],
                    top: 0
                },
                grid: {
                    left: '3%',
                    right: '4%',
                    bottom: '3%',
                    containLabel: true
                },
                xAxis: {
                    type: 'category',
                    boundaryGap: false,
                    data: initialData.times
                },
                yAxis: [
                    {
                        type: 'value',
                        name: '温度(°C)',
                        min: 15,
                        max: 35,
                        position: 'left',
                        axisLine: {
                            lineStyle: {
                                color: '#165DFF'
                            }
                        }
                    },
                    {
                        type: 'value',
                        name: '湿度(%)',
                        min: 30,
                        max: 80,
                        position: 'right',
                        axisLine: {
                            lineStyle: {
                                color: '#36CFC9'
                            }
                        }
                    }
                ],
                series: [
                    {
                        name: '温度(°C)',
                        type: 'line',
                        data: initialData.temps,
                        symbol: 'none',
                        lineStyle: {
                            width: 2,
                            color: '#165DFF'
                        },
                        areaStyle: {
                            color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                                { offset: 0, color: 'rgba(22, 93, 255, 0.2)' },
                                { offset: 1, color: 'rgba(22, 93, 255, 0)' }
                            ])
                        }
                    },
                    {
                        name: '湿度(%)',
                        type: 'line',
                        yAxisIndex: 1,
                        data: initialData.humis,
                        symbol: 'none',
                        lineStyle: {
                            width: 2,
                            color: '#36CFC9'
                        },
                        areaStyle: {
                            color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                                { offset: 0, color: 'rgba(54, 207, 201, 0.2)' },
                                { offset: 1, color: 'rgba(54, 207, 201, 0)' }
                            ])
                        }
                    }
                ]
            };
            
            tempHumidityChart.setOption(option);
            
            // 响应窗口大小变化
            window.addEventListener('resize', () => {
                tempHumidityChart.resize();
            });
        }
        
        // 生成时间序列数据
        function generateTimeSeriesData(points) {
            const times = [];
            const temps = [];
            const humis = [];
            
            const now = new Date();
            
            for (let i = points - 1; i >= 0; i--) {
                const time = new Date(now - i * 60 * 1000); // 每分钟一个点
                const hour = time.getHours().toString().padStart(2, '0');
                const minute = time.getMinutes().toString().padStart(2, '0');
                times.push(`${hour}:${minute}`);
                
                // 生成有波动的温度数据 (23-27°C)
                const baseTemp = 25;
                temps.push((baseTemp + (Math.random() * 4 - 2)).toFixed(1));
                
                // 生成有波动的湿度数据 (40-60%)
                const baseHumi = 50;
                humis.push((baseHumi + (Math.random() * 20 - 10)).toFixed(0));
            }
            
            return { times, temps, humis };
        }
        
        // 更新图表数据
        function updateChartData(range) {
            let points = 60; // 默认1小时数据
            
            if (range === 'day') {
                points = 24; // 24小时，每小时一个点
            } else if (range === 'week') {
                points = 7; // 7天，每天一个点
            }
            
            const newData = generateTimeSeriesData(points);
            
            tempHumidityChart.setOption({
                xAxis: {
                    data: newData.times
                },
                series: [
                    {
                        data: newData.temps
                    },
                    {
                        data: newData.humis
                    }
                ]
            });
        }
        
        // 开始定时更新数据
        function startDataUpdate() {
            // 清除已有的定时器
            if (updateInterval) {
                clearInterval(updateInterval);
            }
            
            // 立即更新一次
            updateSensorData();
            
            // 每3秒更新一次数据
            updateInterval = setInterval(() => {
                updateSensorData();
            }, 3000);
        }
        
        // 检查MQTT连接状态
        function checkMqttConnection() {
            // 实际项目中应该从服务器获取MQTT连接状态
            fetch(`${SERVER_URL}/?action=get_mqtt_status`)
                .then(response => response.json())
                .then(data => {
                    const statusEl = document.getElementById('mqtt-server-status');
                    if (data.connected) {
                        statusEl.textContent = '已连接';
                        statusEl.className = 'text-success';
                    } else {
                        statusEl.textContent = '未连接';
                        statusEl.className = 'text-danger';
                        showNotification('连接警告', 'MQTT服务器连接已断开', 'warning');
                    }
                })
                .catch(error => {
                    console.error('检查MQTT连接失败:', error);
                    const statusEl = document.getElementById('mqtt-server-status');
                    statusEl.textContent = '连接未知';
                    statusEl.className = 'text-warning';
                });
        }
        
        // 更新传感器数据（从服务器获取）
        function updateSensorData() {
            fetch(`${SERVER_URL}/?action=get_shmem_data`)
                .then(response => {
                    if (!response.ok) {
                        throw new Error('网络响应不正常');
                    }
                    return response.json();
                })
                .then(data => {
                    // 更新MQTT状态显示
                    document.getElementById('mqtt-server-status').textContent = '已连接';
                    
                    // 处理服务器返回的STM32设备数据
                    if (data.stm32 && data.stm32.data) {
                        data.stm32.data.forEach(device => {
                            // 更新在线设备数量
                            if (device.key === 1001 && device.value === 1) {
                                document.getElementById('online-devices').textContent = 
                                    (parseInt(document.getElementById('online-devices').textContent) || 0) + 1;
                            }
                            
                            // 根据设备类型设置显示文本
                            let displayText = '';
                            if (device.type === 0) { // 布尔类型
                                displayText = device.value === 1 ? '开启' : '关闭';
                                // 特殊设备的状态文本
                                if (device.key === 1003) {
                                    displayText = device.value === 1 ? '已开锁' : '已关锁';
                                } else if (device.key === 1004) {
                                    displayText = device.value === 1 ? '有人' : '无人';
                                }
                            } else if (device.type === 1) { // 浮点类型
                                displayText = device.key === 1007 ? `${device.floatValue.toFixed(1)}°C` : 
                                              `${device.floatValue.toFixed(0)}%`;
                            }
                            
                            deviceData[device.key] = {
                                value: device.floatValue || device.value,
                                text: displayText,
                                type: device.type === 0 ? 'bool' : 'float'
                            };
                        });
                    }
                    
                    // 处理modbus设备数据
                    if (data.modbus && data.modbus.data) {
                        data.modbus.data.forEach(device => {
                            deviceData[device.key] = {
                                value: device.value,
                                text: device.key === 2001 ? 
                                      (device.value === 11 ? '制冷' : device.value === 22 ? '制热' : '除湿') : 
                                      `${device.value}%`,
                                type: 'int'
                            };
                        });
                    }
                    
                    // 处理metaServer设备数据
                    if (data.metaServer && data.metaServer.data) {
                        data.metaServer.data.forEach(device => {
                            let displayText = '';
                            if (device.key === 3001) {
                                displayText = device.value === 0 ? '无检测' : 
                                              device.value === 1 ? '检测到1人' : '多人检测';
                            } else if (device.key === 3002) {
                                displayText = device.value === 0 ? '正常' : '异常';
                            } else if ([3003, 3005].includes(device.key)) {
                                displayText = `${device.value}%`;
                            } else {
                                displayText = device.value === 1 ? '开启' : '关闭';
                            }
                            
                            deviceData[device.key] = {
                                value: device.value,
                                text: displayText,
                                type: 'int'
                            };
                        });
                    }
                    
                    // 更新设备显示
                    updateDeviceDisplays();
                    logOperation('已从服务器更新设备数据');
                })
                .catch(error => {
                    console.error('获取数据失败:', error);
                    document.getElementById('mqtt-server-status').textContent = '连接失败';
                    showNotification('连接失败', '无法从服务器获取数据', 'error');
                });
        }
        
        // 更新监控画面
        function updateMonitoringImage() {
            // 重新加载iframe以刷新视频流
            const iframe = document.querySelector('.monitor-area iframe');
            const src = iframe.src;
            iframe.src = '';
            setTimeout(() => {
                iframe.src = src;
            }, 100);
            logOperation('监控画面已更新');
        }
        
        // 更新设备显示
        function updateDeviceDisplays() {
            // 更新快速状态卡片
            document.getElementById('current-temp').textContent = `${deviceData['1007'].value}°C`;
            document.getElementById('current-humidity').textContent = `${deviceData['1008'].value}%`;
            
            // 更新所有设备显示
            Object.keys(deviceData).forEach(key => {
                const statusEl = document.getElementById(`status-${key}`);
                const valueEl = document.getElementById(`value-${key}`);
                const displayEl = statusEl || valueEl;
                
                if (displayEl) {
                    displayEl.textContent = deviceData[key].text;
                    
                    // 更新状态指示器颜色
                    if (deviceData[key].type === 'bool') {
                        const indicatorEl = displayEl.parentElement.querySelector('.status-indicator');
                        if (indicatorEl) {
                            if (deviceData[key].value) {
                                indicatorEl.className = 'status-indicator bg-success mr-1';
                                displayEl.className = 'text-success';
                            } else {
                                indicatorEl.className = 'status-indicator bg-danger mr-1';
                                displayEl.className = 'text-danger';
                            }
                        }
                    }
                }
                
                // 更新滑块值
                const sliderEl = document.querySelector(`.device-slider[data-key="${key}"]`);
                if (sliderEl && deviceData[key].type === 'int') {
                    sliderEl.value = deviceData[key].value;
                }
                
                // 更新开关状态
                const toggleEl = document.querySelector(`.device-toggle[data-key="${key}"]`);
                if (toggleEl && deviceData[key].type === 'bool') {
                    toggleEl.checked = deviceData[key].value;
                }
                
                // 更新命令按钮状态
                if (deviceData[key].type === 'int' && key === '2001') {
                    document.querySelectorAll(`.device-command[data-key="${key}"]`).forEach(btn => {
                        if (parseInt(btn.getAttribute('data-cmd')) === deviceData[key].value) {
                            btn.className = 'device-command px-3 py-1 text-xs bg-primary text-white rounded-full';
                        } else {
                            btn.className = 'device-command px-3 py-1 text-xs bg-gray-100 hover:bg-gray-200 rounded-full transition-all duration-300';
                        }
                    });
                }
            });
        }
        
        // 处理设备开关
        function handleDeviceToggle(e) {
            const key = e.target.dataset.key;
            const isOn = e.target.checked;
            
            // 发送命令到设备
            simulateDeviceCommand(key, isOn ? 1 : 0).then(success => {
                if (success) {
                    // 更新设备数据
                    deviceData[key].value = isOn;
                    
                    // 更新状态文本
                    const deviceName = document.querySelector(`[data-key="${key}"]`).closest('.device-card-hover').querySelector('h3').textContent;
                    if (isOn) {
                        deviceData[key].text = key === '1003' ? '已开锁' : 
                                             key === '1005' ? '已开启' : 
                                             key === '2003' ? '开启' : 
                                             key === '3004' ? '开启' : '开启';
                        showNotification('操作成功', `${deviceName}已开启`, 'success');
                    } else {
                        deviceData[key].text = key === '1003' ? '已关锁' : 
                                             key === '1005' ? '已关闭' : 
                                             key === '2003' ? '关闭' : 
                                             key === '3004' ? '关闭' : '关闭';
                        showNotification('操作成功', `${deviceName}已关闭`, 'success');
                    }
                    
                    // 更新显示
                    updateDeviceDisplays();
                    logOperation(`设备[${key}:${deviceName}]已${isOn ? '开启' : '关闭'}`);
                } else {
                    // 操作失败，恢复开关状态
                    e.target.checked = !isOn;
                    showNotification('操作失败', '设备控制命令发送失败', 'error');
                }
            });
        }
        
        // 处理设备命令按钮
        function handleDeviceCommand(e) {
            const key = e.target.dataset.key;
            const cmd = parseInt(e.target.dataset.cmd);
            const deviceName = e.target.closest('.device-card-hover').querySelector('h3').textContent;
            const cmdText = e.target.textContent;
            
            // 发送命令到设备
            simulateDeviceCommand(key, cmd).then(success => {
                if (success) {
                    // 更新设备数据
                    deviceData[key].value = cmd;
                    deviceData[key].text = cmdText;
                    
                    // 更新显示
                    updateDeviceDisplays();
                    showNotification('操作成功', `${deviceName}已切换为${cmdText}`, 'success');
                    logOperation(`设备[${key}:${deviceName}]已切换为${cmdText}`);
                } else {
                    showNotification('操作失败', '设备控制命令发送失败', 'error');
                }
            });
        }
        
        // 处理设备滑块变化(实时)
        function handleDeviceSlider(e) {
            const key = e.target.dataset.key;
            const value = parseInt(e.target.value);
            const statusEl = document.getElementById(`status-${key}`);
            
            if (statusEl) {
                statusEl.textContent = `${value}%`;
            }
        }
        
        // 处理设备滑块确认
        function handleDeviceSliderChange(e) {
            const key = e.target.dataset.key;
            const value = parseInt(e.target.value);
            const deviceName = e.target.closest('.device-card-hover').querySelector('h3').textContent;
            
            // 发送命令到设备
            simulateDeviceCommand(key, value).then(success => {
                if (success) {
                    // 更新设备数据
                    deviceData[key].value = value;
                    deviceData[key].text = `${value}%`;
                    
                    // 更新显示
                    updateDeviceDisplays();
                    showNotification('操作成功', `${deviceName}已调整为${value}%`, 'success');
                    logOperation(`设备[${key}:${deviceName}]已调整为${value}%`);
                } else {
                    // 操作失败，恢复滑块值
                    e.target.value = deviceData[key].value;
                    showNotification('操作失败', '设备控制命令发送失败', 'error');
                }
            });
        }
        
        // 发送设备命令到服务器
        function simulateDeviceCommand(deviceKey, command) {
            // 确定设备类型
            let deviceType = 'stm32';
            if (deviceKey.startsWith('200')) {
                deviceType = 'modbus';
            } else if (deviceKey.startsWith('300')) {
                deviceType = 'metaServer';
            }
            
            // 构建命令JSON
            const commandData = {};
            commandData[deviceType] = {
                key: parseInt(deviceKey),
                value: command
            };
            
            return fetch(`${SERVER_URL}/?action=control_device`, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify(commandData)
            })
            .then(response => {
                if (!response.ok) {
                    throw new Error('命令发送失败');
                }
                return response.json();
            })
            .then(data => {
                return data.status === 0;
            })
            .catch(error => {
                console.error('命令发送失败:', error);
                return false;
            });
        }
        
        // 显示通知
        function showNotification(title, message, type = 'success') {
            const notification = document.getElementById('notification');
            const icon = document.getElementById('notification-icon');
            const titleEl = document.getElementById('notification-title');
            const messageEl = document.getElementById('notification-message');
            
            // 设置通知类型
            if (type === 'success') {
                icon.className = 'w-8 h-8 rounded-full flex items-center justify-center mr-3 bg-success/10 text-success';
                icon.innerHTML = '<i class="fa fa-check"></i>';
            } else if (type === 'error') {
                icon.className = 'w-8 h-8 rounded-full flex items-center justify-center mr-3 bg-danger/10 text-danger';
                icon.innerHTML = '<i class="fa fa-times"></i>';
            } else if (type === 'warning') {
                icon.className = 'w-8 h-8 rounded-full flex items-center justify-center mr-3 bg-warning/10 text-warning';
                icon.innerHTML = '<i class="fa fa-exclamation"></i>';
            }
            
            // 设置内容
            titleEl.textContent = title;
            messageEl.textContent = message;
            
            // 显示通知
            notification.classList.remove('translate-x-full');
            
            // 3秒后自动隐藏
            setTimeout(hideNotification, 3000);
        }
        
        // 隐藏通知
        function hideNotification() {
            const notification = document.getElementById('notification');
            notification.classList.add('translate-x-full');
        }
        
        // 记录操作日志
        function logOperation(message) {
            const logContainer = document.getElementById('operation-log');
            const now = new Date();
            const timeStr = now.toTimeString().slice(0, 8);
            
            // 创建日志项
            const logItem = document.createElement('div');
            logItem.className = 'text-sm text-gray-500 mb-2 animate-fadeIn';
            logItem.innerHTML = `<span class="text-gray-400">[${timeStr}]</span> ${message}`;
            
            // 添加到日志容器顶部
            logContainer.insertBefore(logItem, logContainer.firstChild);
            
            // 限制日志数量
            if (logContainer.children.length > 20) {
                logContainer.removeChild(logContainer.lastChild);
            }
        }
        
        // 页面卸载时清理
        window.addEventListener('beforeunload', function() {
            if (updateInterval) {
                clearInterval(updateInterval);
            }
        });
    </script>
</body>
</html>
